<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    dialog-width="600px"
    :page-show="pageShow"
    @dialog-close="dialogClose"
  >
    <template #toolPanel />
    <template #searchPanel>
      <search-panel :show-add-button="isCompetence" :show-search-button="true" @search="search"
                    :showSuccessOrderList="isCompetence" @successOrderList="successOrderList"
                    :showFailtOrderList="isCompetence" @failtOrderList="failtOrderList"
                    :showStatusCallBacks="isCompetence" @statusCallBacks="statusCallBacks"
                    :showMinuteHandleSearch="isCompetence" @minuteHandleSearch="minuteHandleSearch"
                    :showExportDataButton="true" @exportData="exportdataFlowOrder"
                    @repeatFlowOrder="repeatFlowOrder" :showRepeatFlowOrder="isCompetence"
                    labelWidth="73"
                    :left="true">
        <el-form-item label="运营商:" prop="operatoruid">
          <el-select v-model="filters.operatoruid" style="width: 212px;" collapse-tags clearable filterable placeholder="请选择运营商">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in operator"
              :key="item.operatoruid"
              :label="item.operatorname"
              :value="item.operatoruid">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分销商:" prop="useruuid" v-show="isCompetence">
          <el-select v-model="filters.useruuid" clearable style="width: 212px;" filterable collapse-tags placeholder="请选择分销商" >
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in users"
              :key="item.user.useruuid"
              :label="item.user.username"
              :value="item.user.useruuid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份:" prop="provinceuuid">
          <el-select v-model="filters.provinceuuid" clearable style="width: 212px;" filterable collapse-tags placeholder="请选择省份">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in info"
              :key="item.provinceuuid"
              :label="item.provincename"
              :value="item.provincename">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型:" prop="busuuid"   v-show="isShow" >
          <el-select v-model="filters.busuuid" filterable clearable style="width: 212px;" collapse-tags placeholder="请选择业务类型">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in bus"
              :key="item.busuuid"
              :label="item.busname"
              :value="item.busuuid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商家单号:">
          <el-input v-model="filters.downreqid" style="width: 212px;" clearable placeholder="商家订单号"   ></el-input>
        </el-form-item>
        <el-form-item label="充值号码:">
          <el-input v-model="filters.phoneNum" style="width: 212px;" clearable placeholder="充值号码"></el-input>
        </el-form-item>
        <el-form-item label="面值:">
<!--          <el-input v-model="filters.downfacevalue" clearable placeholder="面值"></el-input>-->
          <el-select v-model="filters.downfacevalue" clearable style="width: 212px;" filterable placeholder="面值">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in downfacevalues"
              :key="item.id"
              :label="item.id"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态:"   >
          <el-select v-model="filters.statu" style="width: 212px;" filterable clearable collapse-tags placeholder="请选择订单状态">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in status"
              :key="item.id"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回调状态:"   >
          <el-select v-model="filters.callstatus" style="width: 212px;" filterable clearable  collapse-tags placeholder="请选择回调状态">
            <el-option value="-1" label="全部">全部</el-option>
            <el-option value="0" label="等待回调">等待回调</el-option>
            <el-option value="1" label="回调成功">回调成功</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:">
          <el-date-picker type="datetime" placeholder="开始时间" clearable format="yyyy-MM-dd HH:mm:ss"   v-model="filters.createtime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间:">
          <el-date-picker type="datetime" placeholder="结束时间" clearable format="yyyy-MM-dd HH:mm:ss"   v-model="filters.endtime" style="width: 100%;"></el-date-picker>
        </el-form-item>
      </search-panel>
    </template>
    <template #contentPanel>
      <data-table
        :value="tableData"
        :total-count="totalCount"
        :has-action="true"
        :width="isCompetence ? 210 : 80"
        :current="start"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :isShowSelection="true"
        @selection-change="selsChange"
      >
        <template #action="{row}">
          <el-button size="small" round @click="statusCallBack(row)">回调</el-button>
          <el-button size="small" round v-if="isCompetence" @click="failtOrder(row)">失败</el-button>
          <el-button size="small" round v-if="isCompetence" @click="successOrder(row)">成功</el-button>

        </template>
      </data-table>
    </template>

    <template #dialog>
    </template>

  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
import {findDownOrder,successOrder,successOrderList,failtOrderList,failtOrder,statusCallBack,exportdataFlowOrder,repeatFlowOrder} from '@/api/downapi'
import {findOpeProBusShop,findAllDownShopInfo,findAllChannel,findPageOperator} from '@/api/utilsapi'
import moment from 'moment';
import util from "../../../utils/util";

export default {
  name: 'downOrder',
  mixins: [
    baseMixin({
      idName: 'id',
      refresh: '',
      findData: findDownOrder,
      format(res) {
        return res.map(data => {
          return data
        })
      }
    })
  ],
  data() {
    return {
      buttons: [],
      pageShow: true,
      dialogData:{},
      isShow:true,
      isCompetence: util.checkRoleAdminAndSuper() ? true : false,
      downfacevalues:[],
      tableColumnAttributes: [
        { name: '分销商', value: 'username', formatter : this.userNameFormatter , width:100},
        { name: '运营商', value: 'operatorname' , width:80},
        { name: '省份', value: 'province' , width:60 },
        { name: '地市', value: 'cityName' , width:60 },
        { name: '业务类型', value: 'busname', formatter : this.busnameFormatter },
        { name: '充值号码', value: 'dowonphonenum' ,width:110 },
        { name: '实际金额', value: 'rechargeamount' },
        { name: '充值名称', value: 'name' , width: 105 },
        { name: '充值区域名称', value: 'areaName' , width: 105 },
        { name: '充值类型', value: 'rechargeType' , width: 105 },
        { name: '充值服务器', value: 'server' , width: 105 },
        { name: '来源IP', value: 'sourceIp' , width: 105 },
        { name: '充值数量', value: 'downrechargenum' },
        { name: '扣款金额', value: 'discountAmount' },
        { name: '产品名称', value: 'productName' ,width:130 ,formatter:this.productNameFormatter},
        { name: '折扣', value: 'discount' },
        { name: '面值', value: 'downfacevalue', width:60 ,formatter:this.downfacevalueFormatter},
        { name: '状态', value: 'status' , type:'eltag',width: 90 },
        { name: '回调状态', value: 'callStatus' ,formatter: this.callStatus},
        { name: '充值时间', value: 'createtime' ,width:150},
        { name: '完成时间', value: 'downendtime' ,width:150},
        { name: '产品编码', value: 'downprouuid' ,width:215 ,formatter:this.downprouuidFormatter},
        { name: '商家单号', value: 'downreqid' ,width:215 },
        { name: '备注', value: 'remark' ,width:215 },
        { name: '批次号', value: 'statusremark',width:210  }
      ],
      filters: {
        downreqid: '',
        busuuid:'',
        createtime:  moment().subtract('hour', 1).format('YYYY-MM-DD HH:mm:ss'),
        operatoruid:'',
        endtime: moment().add('hour', 6).format('YYYY-MM-DD HH:mm:ss'),
        provinceuuid:'',
        useruuid:'',
        phoneNum:'',
        downorderuuid:'',
        statu:'',
        callstatus:'',
        downfacevalue:''
      },
      status:[{id:"1",name:"充值中",value:"1"},{id:"2",name:"充值成功",value:"2"} ,
        {id:"3",name:"充值失败",value:"3"},
        {id:"5",name:"等待充值",value:"5"},
        {id:"9",name:"缓存订单",value:"9"},
        {id:"10",name:"压单 ",value:"10"},{id:"11",name:"人工 ",value:"11"}],
      bus: [],
      info:[],
      users:[],
      operator: [],
      sels: [],//列表选中列
    }
  },
  methods: {
    async search(form,minute){
      let para = {
        start: this.start,
        pageSize: this.pageSize,
        useruuid:this.filters.useruuid == "0" ? "": this.filters.useruuid, //JSON.parse(sessionStorage.getItem("user")).useruuid,
        busuuid:this.filters.busuuid == "0" ? "" : this.filters.busuuid,
        provinceuuid:this.filters.provinceuuid == "0" ? "" : this.filters.provinceuuid,
        operatoruid:this.filters.operatoruid == "0" ? "" : this.filters.operatoruid,
        downreqid:this.filters.downreqid,
        phoneNum:this.filters.phoneNum,
        downorderuuid:this.filters.downorderuuid,
        status : this.filters.statu == "0" ? "" : this.filters.statu,
        createtime: (this.filters.createtime == "" || this.filters.createtime == undefined) ? "" : moment(this.filters.createtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        endtime: (this.filters.endtime == "" || this.filters.endtime == undefined) ? "" : moment(this.filters.endtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        callstatus:this.filters.callstatus == "-1" ? "" : this.filters.callstatus,
        downfacevalue:this.filters.downfacevalue
      };
      if(minute){
        para.minute = true;
        para.createtime = "";
      }
      this.searchOptions = para;
      if(this.searchOptions.phoneNum){
        this.start = 1
        console.log("phoneNum:",this.searchOptions.phoneNum,this.start)
      }
      console.log("xxx:",this.searchOptions)
      this.setTableData()
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    successOrderList(){
      if(this.sels != null && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].dowonphonenum+",\n";
        }
        this.$confirm('确认手工批量成功订单吗？订单电话号码:'+str, '提示', {roundButton:true}).then(() => {
          let para = {
            downorderuuids: this.sels
          };
          successOrderList(para).then((datas) => {
            this.resultSuccess(datas);
          });
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    failtOrderList(){
      if(this.sels != null && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].dowonphonenum+",\n";
        }
        this.$confirm('确认批量失败订单吗？订单电话号码:'+str, '提示', {roundButton:true}).then(() => {
          let para = {
            downorderuuids: this.sels
          };
          failtOrderList(para).then((datas) => {
             this.resultSuccess(datas);
          });
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    statusCallBacks(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].dowonphonenum+",\n";
        }
        this.$confirm('确认批量回调订单吗？订单电话号码:'+str, '提示', {roundButton:true}).then(() => {
          for(var i = 0 ; i < this.sels.length;i++){
            let para = {
              downorderuuid: this.sels[i].downorderuuid
            };
            statusCallBack(para).then((datas) => {
              let {message, code, data} = datas;
              if (code !== "0") {
                this.showMsg(message,"error");
              }
            });
          }
          this.showMsg("回调成功","info");
          this.search();
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    minuteHandleSearch(){
      this.search(this.form,true);
    },
    exportdataFlowOrder(){
      let para = {
        useruuid:this.filters.useruuid == "0" ? "": this.filters.useruuid, //JSON.parse(sessionStorage.getItem("user")).useruuid,
        busuuid:this.filters.busuuid == "0" ? "" : this.filters.busuuid,
        provinceuuid:this.filters.provinceuuid == "0" ? "" : this.filters.provinceuuid,
        operatoruid:this.filters.operatoruid == "0" ? "" : this.filters.operatoruid,
        downreqid:this.filters.downreqid,
        phoneNum:this.filters.phoneNum,
        downorderuuid:this.filters.downorderuuid,
        status : this.filters.statu == "0" ? "" : this.filters.statu,
        createtime: (!this.filters.createtime || !this.filters.createtime) ? "" : moment(this.filters.createtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        endtime: this.filters.endtime == "" ? "" : moment(this.filters.endtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        callstatus:this.filters.callstatus == "-1" ? "" : this.filters.callstatus,
        downfacevalue:this.filters.downfacevalue
      };
      exportdataFlowOrder(para).then(res => {
        let {message, code, data} = res;
        if (code !== "0") {
          this.showMsg(message,"error");
        } else {
          if(data.path){
            this.showMsg("订单导出成功,请稍后进入导出列表下载","info");
          }
        }
      });
    },
    repeatFlowOrder(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].dowonphonenum+",\n";
        }
        this.$confirm('确认批量重提订单吗？订单电话号码:'+str, '提示', {roundButton:true}).then(() => {
          for(var i = 0 ; i < this.sels.length;i++){
            let para = {
              downorderuuid: this.sels[i].downorderuuid
            };
            repeatFlowOrder(para).then((datas) => {
              let {message, code, data} = datas;
              if (code !== "0") {
                this.showMsg(message,"error");
              }
            });
          }
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    userNameFormatter(row){
      return row.userFlow.username;
    },
    busnameFormatter(row){
      return row && row.downShopProduct ? row.downShopProduct.businessType.busname : "";
    },
    productNameFormatter(row){
      return row && row.downShopProduct ? row.downShopProduct.productName : "";
    },
    downfacevalueFormatter(row){
      return row && row.downShopProduct ? row.downShopProduct.downfacevalue : "";
    },
    downprouuidFormatter(row){
      return row && row.downShopProduct ? row.downShopProduct.downprouuid : "";
    },
    failtOrder(row){
      this.$confirm('确认手工失败订单吗？订单电话号码:'+row.dowonphonenum, '提示', {roundButton:true}).then(() => {
        let para = {
          downorderuuid: row.downorderuuid
        };
        failtOrder(para).then((datas) => {
          this.resultSuccess(datas);
        });
      });
    },
    successOrder(row){
      this.$confirm('确认手工成功订单吗？订单电话号码:'+row.dowonphonenum, '提示', {roundButton:true}).then(() => {
        let para = {
          downorderuuid: row.downorderuuid
        };
        successOrder(para).then((datas) => {
          this.resultSuccess(datas);
        });
      });
    },
    callStatus: function (row, column) {
      return row.callStatus === 1 ? '回调成功' : row.callStatus ===  0 ? '等待回调' : row.callStatus ===  2 ? "订单失败": '未知';
    },
    statusCallBack(row) {
      this.$confirm('确认手工回调订单吗？订单电话号码:'+row.dowonphonenum, '提示', {roundButton:true}).then(() => {
        let para = {
          downorderuuid: row.downorderuuid
        };
        statusCallBack(para).then((datas) => {
          this.resultSuccess(datas)
        });
      });
    },
    async findOpeProBusShop(){
      let para = {test: ''};
      const result = await findOpeProBusShop(para);
      if(result.code == "0"){
        this.info = result.data.info;
        this.bus = result.data.bus;
      }
    },
    async findPageOperator(){
      let para = {
        start: 1,
        pageSize:101,
        operatorname:'',
      };
      findPageOperator(para).then((datas) => {
        let { message, code, data } = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else if(data && data.result){
          this.operator = data.result;
        }
      });
    },
    async findAllChannel(){
      let para = {
        province : ""
      };
      const result = await findAllChannel(para);
      if(result && result.data){
        result.data.forEach(item =>{
          this.downfacevalues.push({id:item,value:item});
        });
      }
    },
    async findAllDownShopInfo(){
      let para = {useruuid: this.$store.getters.useruuid};
      const result = await findAllDownShopInfo(para);
      if(result.data){
        this.users = result.data;
      }
    },
  },
  mounted() {
    this.findAllDownShopInfo();
    this.findAllChannel();
    this.findPageOperator();
    this.findOpeProBusShop();
  }
}
</script>
